package thoven.achievement.net.ideapluginachievement.component

import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileDocumentManagerListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectActivity
import com.intellij.openapi.vfs.VirtualFile
import thoven.achievement.net.ideapluginachievement.listener.DocumentChangeListener
import thoven.achievement.net.ideapluginachievement.listener.WindowFocusListener
import thoven.achievement.net.ideapluginachievement.service.AchievementNotificationService
import thoven.achievement.net.ideapluginachievement.service.CodeStatsService

/**
 * 项目启动活动
 * 用于初始化监听器和服务
 */
class AchievementProjectActivity : ProjectActivity {
    
    private val LOG = logger<AchievementProjectActivity>()
    
    override suspend fun execute(project: Project) {
        LOG.info("初始化代码成就插件...")
        
        try {
            // 初始化服务
            val codeStatsService = CodeStatsService.getInstance(project)
            val notificationService = AchievementNotificationService.getInstance(project)
            
            // 重置每日计数器（如果日期已变更）
            codeStatsService.resetDailyCounters()
            
            // 注册各种监听器
            ApplicationManager.getApplication().invokeLater {
                registerDocumentListener(project)
                registerFileListener(project)
                registerWindowFocusListener(project)
            }
            
            // 显示欢迎通知（可选）
            val consecutiveDays = codeStatsService.getConsecutiveDays()
            if (consecutiveDays > 1) {
                notificationService.showConsecutiveDaysNotification(consecutiveDays)
            }
            
            LOG.info("代码成就插件初始化完成")
        } catch (e: Exception) {
            LOG.error("初始化代码成就插件时出错", e)
        }
    }
    
    /**
     * 注册文档监听器
     */
    private fun registerDocumentListener(project: Project) {
        val documentListener = DocumentChangeListener(project)
        
        EditorFactory.getInstance().eventMulticaster.addDocumentListener(
            documentListener,
            project
        )
        
        LOG.info("文档监听器已注册")
    }
    
    /**
     * 注册文件保存监听器
     * 用于检测文件保存操作
     */
    private fun registerFileListener(project: Project) {
        val codeStatsService = CodeStatsService.getInstance(project)
        
        val fileSaveListener = object : FileDocumentManagerListener {
            override fun beforeDocumentSaving(document: com.intellij.openapi.editor.Document) {
                // 文件保存时记录
                codeStatsService.recordSave()
                
                val file = FileDocumentManager.getInstance().getFile(document)
                if (file != null) {
                    LOG.debug("文件已保存: ${file.name}")
                }
            }
        }
        
        // 订阅文件保存事件
        ApplicationManager.getApplication().messageBus.connect(project)
            .subscribe(FileDocumentManagerListener.TOPIC, fileSaveListener)
        
        LOG.info("文件保存监听器已注册")
    }
    
    /**
     * 注册窗口焦点监听器
     * 用于检测"鸡你太美"成就
     */
    private fun registerWindowFocusListener(project: Project) {
        try {
            val windowFocusListener = WindowFocusListener(project)
            windowFocusListener.register()
            
            LOG.info("窗口焦点监听器已注册")
        } catch (e: Exception) {
            LOG.error("注册窗口焦点监听器时出错", e)
        }
    }
} 
